import 'package:flutter/material.dart';

import 'package:sow_app_core/sow_app_core.dart';

class ChipFilter extends StatefulWidget {
  const ChipFilter(
      {Key? key,
      required this.onItemSelected,
      required this.selections,
      this.tight = false})
      : super(key: key);
  final bool tight;
  final Set<ChipFilterEntry> selections;
  final void Function(ChipFilterEntry) onItemSelected;
  @override
  State createState() => ChipFilterState();
}

class ChipFilterState extends State<ChipFilter> {
  ChipFilterEntry? _selected;

  Iterable<Widget> get chipWidgets {
    return widget.selections.map((ChipFilterEntry chip) {
      return Padding(
        padding: const EdgeInsets.only(left: 8.0),
        child: FilterChip(
          showCheckmark: false,
          visualDensity: widget.tight
              ? const VisualDensity(horizontal: 0.0, vertical: -4)
              : null,
          label: Text(chip.name),
          selected: _selected?.value == chip.value,
          onSelected: (bool value) {
            setState(() {
              _selected = chip;
              widget.onItemSelected(_selected!);
            });
          },
        ),
      );
    });
  }

  @override
  void initState() {
    if (widget.selections.isNotEmpty) {
      _selected = widget.selections.first;
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: widget.tight ? 32 : 64,
      child: ListView(
        scrollDirection: Axis.horizontal,
        children: chipWidgets.toList(),
      ),
    );
  }
}
